package com.hundsun.yr.universal.p2p.idcardscan;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.graphics.drawable.GradientDrawable;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.Size;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.hundsun.mobile.zwgt.R;
import com.ym.idcard.reg.bean.IDCard;
import com.ym.idcard.reg.engine.OcrEngine;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class ScanCardActivity_q extends Activity implements Callback, PreviewCallback {

//    private ImageView back;
    private Camera camera;
    private TextView copyright_label;
    private int counter = 0;
//    private ImageView flash;
    private int height;
    private ImageView take_photo;
    private boolean isFatty = false;
    private boolean isROI = false;
    private boolean isShowBorder = false;
    private List<Size> list;
    private ViewfinderView myView;
    private int preHeight = 0;
    private int preWidth = 0;
    private RelativeLayout re_c;
    public int srcHeight;
    public int srcWidth;
    public int surfaceHeight;
    private SurfaceHolder surfaceHolder;
    private SurfaceView surfaceView;
    public int surfaceWidth;
    private Timer time;
    private TimerTask timer;
    private int width;
    public static byte[] tackData = null;
    public static  Bitmap bitmap = null;
    CardInfo cardInfo = new CardInfo("","");
    private boolean isResult = false;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_scan_camera);
        setScreenSize(this);
        findView();
    }

    @SuppressLint({"NewApi"})
    private void setScreenSize(Context context) {
        int x;
        int y;
        Display display = ((WindowManager) context.getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
        if (VERSION.SDK_INT >= 13) {
            Point screenSize = new Point();
            if (VERSION.SDK_INT >= 17) {
                display.getRealSize(screenSize);
                x = screenSize.x;
                y = screenSize.y;
            } else {
                display.getSize(screenSize);
                x = screenSize.x;
                y = screenSize.y;
            }
        } else {
            x = display.getWidth();
            y = display.getHeight();
        }
        this.srcWidth = x;
        this.srcHeight = y;
    }

    private void findView() {
        take_photo = (ImageView) findViewById(R.id.take_photo);
        byte strokeWidth = 3;
        byte roundRadius = 20;
        int strokeColor = Color.parseColor("#fb6d59");
        int fillColor = Color.parseColor("#ffffff");
        GradientDrawable takegd = new GradientDrawable();
        takegd.setColor(fillColor);
        takegd.setCornerRadius((float)roundRadius);
        takegd.setStroke(strokeWidth, strokeColor);
        this.surfaceView = (SurfaceView) findViewById(R.id.surfaceViwe);
        this.re_c = (RelativeLayout) findViewById(R.id.re_c);
        this.copyright_label = (TextView) findViewById(R.id.copyright_label);
//        this.back = (ImageView) findViewById(R.id.top_back);
//        this.flash = (ImageView) findViewById(R.id.top_flash);
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        this.width = metric.widthPixels;
        this.height = metric.heightPixels;
        if (this.width * 3 == this.height * 4) {
            this.isFatty = true;
        }
        LayoutParams layoutParams;
        int help_word_w = (int) (((double) this.width) * 0.474609375d);
        int help_word_h = (int) (((double) help_word_w) * 0.05185185185185185d);
        layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
        if (this.isFatty) {
            layoutParams.bottomMargin = (this.height / 10) - (help_word_h / 2);
        } else {
            layoutParams.bottomMargin = (this.height / 20) - (help_word_h / 2);
        }
        this.copyright_label.setLayoutParams(layoutParams);
        this.surfaceHolder = this.surfaceView.getHolder();
        this.surfaceHolder.addCallback(this);
        this.surfaceHolder.setType(3);
//        this.back.setOnClickListener(new OnClickListener() {
//            public void onClick(View v) {
//                if(camera != null) {
//                    camera.setPreviewCallback(null);
//                    camera.stopPreview();
//                    camera.release();
//                    camera = null;
//                }
//                finish();
//            }
//        });
//        this.flash.setOnClickListener(new OnClickListener() {
//            public void onClick(View v) {
//                if (!ScanCardActivity_q.this.getPackageManager().hasSystemFeature("android.hardware.camera.flash")) {
//                    Toast.makeText(ScanCardActivity_q.this, getResources().getString(getResources().getIdentifier("toast_flash", "string", ScanCardActivity_q.this.getApplication().getPackageName())), Toast.LENGTH_SHORT).show();
//                } else if (ScanCardActivity_q.this.camera != null) {
//                    Parameters parameters = ScanCardActivity_q.this.camera.getParameters();
//                    if (parameters.getFlashMode().equals("torch")) {
//                        parameters.setFlashMode("off");
//                        parameters.setExposureCompensation(0);
//                    } else {
//                        parameters.setFlashMode("torch");
//                        parameters.setExposureCompensation(-1);
//                    }
//                    try {
//                        ScanCardActivity_q.this.camera.setParameters(parameters);
//                    } catch (Exception e) {
//                        Toast.makeText(ScanCardActivity_q.this, ScanCardActivity_q.this.getResources().getString(ScanCardActivity_q.this.getResources().getIdentifier("toast_flash", "string", ScanCardActivity_q.this.getApplication().getPackageName())), Toast.LENGTH_SHORT).show();
//                    }
//                    ScanCardActivity_q.this.camera.startPreview();
//                }
//            }
//        });
        take_photo.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if(tackData != null && camera != null){
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = false;
                    options.inPreferredConfig = Bitmap.Config.RGB_565;
                    Size previewSize = camera.getParameters().getPreviewSize();
                    YuvImage yuvimage=new YuvImage(tackData, ImageFormat.NV21, previewSize.width, previewSize.height, null);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    yuvimage.compressToJpeg(new Rect(0, 0, previewSize.width, previewSize.height), 100, baos);  //这里 80 是图片质量，取值范围 0-100，100为品质最高
                    byte[] jdata = baos.toByteArray();
                    Bitmap bitmap = BitmapFactory.decodeByteArray(jdata, 0, jdata.length, options);
                    if(bitmap == null){
                        return;
                    }
                    Rect rect = myView.getFrame();
//                    Log.e("bitmap==",""+previewSize.width);
//                    Log.e("bitmap==",""+previewSize.height);
//                    Log.e("bitmap==",""+bitmap.getWidth());
//                    Log.e("bitmap==",""+bitmap.getHeight());
                    Bitmap bmp = Bitmap.createBitmap(bitmap, rect.left * previewSize.width / width, rect.top * previewSize.height / height,
                            rect.width() * previewSize.width / width, rect.height() * previewSize.height / height);
                    take_photo.setImageBitmap(bmp);
                }

            }
        });
    }

    public void surfaceCreated(SurfaceHolder holder) {
        if (this.camera == null) {
            try {
                this.camera = Camera.open();
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        try {
            this.camera.setPreviewDisplay(holder);
            this.time = new Timer();
            if (this.timer == null) {
                this.timer = new TimerTask() {
                    public void run() {
                        if (ScanCardActivity_q.this.camera != null) {
                            try {
                                ScanCardActivity_q.this.camera.autoFocus(new AutoFocusCallback() {
                                    public void onAutoFocus(boolean success, Camera camera) {
                                    }
                                });
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                };
            }
            this.time.schedule(this.timer, 500, 2500);
            initCamera(holder);
        } catch (IOException e2) {
            e2.printStackTrace();
        }
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        try {
            if (this.camera != null) {
                holder.removeCallback(this);
                this.camera.setPreviewCallback(null);
                this.camera.stopPreview();
                this.camera.release();
                this.camera = null;
            }
        } catch (Exception e) {
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            try {
                if (this.camera != null) {
                    this.camera.setPreviewCallback(null);
                    this.camera.stopPreview();
                    this.camera.release();
                    this.camera = null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @TargetApi(14)
    private void initCamera(SurfaceHolder holder) {
        Parameters parameters = this.camera.getParameters();
        getCameraPreParameters(this.camera);
        if (!this.isROI) {
            this.isROI = true;
            if (this.isFatty) {
                this.myView = new ViewfinderView(this, this.width, this.height, this.isFatty);
            } else {
                this.myView = new ViewfinderView(this, this.width, this.height);
            }
            this.re_c.addView(this.myView);
        }
        parameters.setPictureFormat(ImageFormat.JPEG);
        parameters.setPreviewSize(this.preWidth, this.preHeight);
        if (parameters.getSupportedFocusModes().contains("continuous-picture")) {
            if (this.time != null) {
                this.time.cancel();
                this.time = null;
            }
            if (this.timer != null) {
                this.timer.cancel();
                this.timer = null;
            }
            parameters.setFocusMode("continuous-picture");
        } else if (parameters.getSupportedFocusModes().contains("auto")) {
            System.out.println("聚焦else");
            parameters.setFocusMode("auto");
        }
        this.camera.setPreviewCallback(this);
        this.camera.setParameters(parameters);
        try {
            this.camera.setPreviewDisplay(holder);
        } catch (IOException e) {
            e.printStackTrace();
        }
        this.camera.startPreview();
    }

    public void onPreviewFrame(byte[] data, Camera scamera) {
        if(isResult){
            return;
        }
        this.tackData = data;
        this.counter++;
        if (this.counter == 2) {
            this.counter = 0;
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = false;
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            Size previewSize = scamera.getParameters().getPreviewSize();
            YuvImage yuvimage=new YuvImage(data, ImageFormat.NV21, previewSize.width, previewSize.height, null);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            yuvimage.compressToJpeg(new Rect(0, 0, previewSize.width, previewSize.height), 100, baos);  //这里 80 是图片质量，取值范围 0-100，100为品质最高
            byte[] jdata = baos.toByteArray();
            Bitmap bmp1 = BitmapFactory.decodeByteArray(jdata, 0, jdata.length, options);
            if(bmp1 == null){
                return;
            }
            Rect rect = myView.getFrame();
            Bitmap bmp = Bitmap.createBitmap(bmp1, rect.left * previewSize.width / width +20, rect.top * previewSize.height / height +20,
                    rect.width() * previewSize.width / width -40, rect.height() * previewSize.height / height -40);

            ByteArrayOutputStream cropStream = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.JPEG,100,cropStream);

            /*身份证扫描核心代码*/
            OcrEngine ocrEngine = new OcrEngine();
            IDCard idCard = ocrEngine.recognize(getApplicationContext(), 2, cropStream.toByteArray(), null);
            if(idCard.getPeriod()!=null  && !idCard.getPeriod().equals("") ){
//                    if(IDCardUtils.isDate(idCard.getPeriod())){}
                ScanCardActivity_q.bitmap = bmp1;
//                Log.e("idCard=====",idCard.getPeriod());
            }
            if(idCard.getCardNo()!=null  && idCard.getCardNo().length()==18 ){
                try {
                    ScanCardActivity_q.bitmap = bmp1;
                    String s = IDCardUtils.IDCardValidate(idCard.getCardNo());
//                    Log.e("idCard=====",idCard.getName());
//                    Log.e("idCard=====",idCard.getCardNo());
                    if(s.equals("")){
                        isResult = true;
                        cardInfo.setNum(idCard.getCardNo());
                        cardInfo.setName(idCard.getName());
                        Intent intent = new Intent();
                        intent.putExtra("card",cardInfo);
                        setResult(RESULT_OK,intent);
                        finish();
                    }


                } catch (ParseException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    protected void onStop() {
        super.onStop();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        try {
            if (camera != null) {
                camera.setPreviewCallback(null);
                camera.stopPreview();
                camera.release();
                camera = null;
            }
        } catch (Exception e) {
        }
    }

    public void getCameraPreParameters(Camera camera) {
        this.isShowBorder = false;
        if ("PLK-TL01H".equals(Build.MODEL)) {
            preWidth = 1920;
            preHeight = 1080;
        } else if ("MI 3".equals(Build.MODEL)) {
            preWidth = 1024;
            preHeight = 576;
        } else {
            // TODO: 2017/8/31 这边可能会奔溃
            list = camera.getParameters().getSupportedPreviewSizes();
            float ratioScreen = ((float) this.srcWidth) / ((float) this.srcHeight);
            int i = 0;
            while (i < this.list.size()) {
                if (ratioScreen == ((float) (this.list.get(i)).width) / ((float) (this.list.get(i)).height) && ((this.list.get(i)).width >= 1280 || (this.list.get(i)).height >= 720)) {
                    if (this.preWidth == 0 && this.preHeight == 0) {
                        this.preWidth = (this.list.get(i)).width;
                        this.preHeight = (this.list.get(i)).height;
                    }
                    if ((this.list.get(0)).width > (this.list.get(this.list.size() - 1)).width) {
                        if (this.preWidth > (this.list.get(i)).width || this.preHeight > (this.list.get(i)).height) {
                            this.preWidth = (this.list.get(i)).width;
                            this.preHeight = (this.list.get(i)).height;
                        }
                    } else if ((this.preWidth < (this.list.get(i)).width || this.preHeight < (this.list.get(i)).height) && this.preWidth < 1280 && this.preHeight < 720) {
                        this.preWidth = (this.list.get(i)).width;
                        this.preHeight = (this.list.get(i)).height;
                    }
                }
                i++;
            }
            if (this.preWidth == 0 || this.preHeight == 0) {
                this.isShowBorder = true;
                this.preWidth = (this.list.get(0)).width;
                this.preHeight = (this.list.get(0)).height;
                i = 0;
                while (i < this.list.size()) {
                    if ((this.list.get(0)).width > (this.list.get(this.list.size() - 1)).width) {
                        if ((this.preWidth >= (this.list.get(i)).width || this.preHeight >= (this.list.get(i)).height) && (this.list.get(i)).width >= 1280) {
                            this.preWidth = (this.list.get(i)).width;
                            this.preHeight = (this.list.get(i)).height;
                        }
                    } else if ((this.preWidth <= (this.list.get(i)).width || this.preHeight <= (this.list.get(i)).height) && this.preWidth < 1280 && this.preHeight < 720 && (this.list.get(i)).width >= 1280) {
                        this.preWidth = (this.list.get(i)).width;
                        this.preHeight = (this.list.get(i)).height;
                    }
                    i++;
                }
            }
            if (this.preWidth == 0 || this.preHeight == 0) {
                this.isShowBorder = true;
                if ((this.list.get(0)).width > (this.list.get(this.list.size() - 1)).width) {
                    this.preWidth = (this.list.get(0)).width;
                    this.preHeight = (this.list.get(0)).height;
                } else {
                    this.preWidth = (this.list.get(this.list.size() - 1)).width;
                    this.preHeight = (this.list.get(this.list.size() - 1)).height;
                }
            }
            if (!this.isShowBorder) {
                this.surfaceWidth = this.srcWidth;
                this.surfaceHeight = this.srcHeight;
            } else if (ratioScreen > ((float) this.preWidth) / ((float) this.preHeight)) {
                this.surfaceWidth = (int) ((((float) this.preWidth) / ((float) this.preHeight)) * ((float) this.srcHeight));
                this.surfaceHeight = this.srcHeight;
            } else {
                this.surfaceWidth = this.srcWidth;
                this.surfaceHeight = (int) ((((float) this.preHeight) / ((float) this.preWidth)) * ((float) this.srcHeight));
            }
        }
    }

    @TargetApi(19)
    public void hiddenVirtualButtons(View mDecorView) {
        if (VERSION.SDK_INT >= 19) {
            mDecorView.setSystemUiVisibility(3334);
        }
    }

}